package com.skynet.automapsql;

import com.skynet.automapsql.interceptor.AutoMapSQLInterceptor;
import com.skynet.automapsql.property.AutoMapSQLProperties;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author Skynet
 * @date 2017年09月14日 14:50
 */

@Configuration
@EnableConfigurationProperties({AutoMapSQLProperties.class})
@AutoConfigureAfter(MybatisAutoConfiguration.class)
public class AutoMapSQLConfiguration {

    @Autowired
    private AutoMapSQLProperties autoMapSQLProperties;

    @Autowired
    private List<SqlSessionFactory> sqlSessionFactoryList;

    @PostConstruct
    public void addMapSQLInterceptor() {
        //是否开启自动SQL装配
        boolean enabled = autoMapSQLProperties.isEnabled();
        if (enabled) {
            Interceptor interceptor = new AutoMapSQLInterceptor();
            for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
                sqlSessionFactory.getConfiguration().addInterceptor(interceptor);
            }
        }
    }

}
